package blog.spring.db.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import blog.core.exception.FormParamErrorException;
import blog.spring.db.dao.ICommentDAO;
import blog.spring.db.entity.Comment;
import blog.spring.db.service.IArticleService;
import blog.spring.db.service.ICommentService;

@Service("commentService")
public class CommentService extends BaseService<Comment> implements
		ICommentService {

	private final ICommentDAO commentDao;
	@Resource
	private IArticleService articleService;
	public static String TYPE_NAME = "评论";

	@Autowired
	public CommentService(ICommentDAO commentDao) {
		super(commentDao, TYPE_NAME);
		this.commentDao = commentDao;
	}

	@Override
	public void save(Comment entity) throws FormParamErrorException {
		if (entity.getArticleInfo() == null && entity.getComment() != null) {// 如果所属文章为空，但是父级不为空
			// 将评论的文章归为父级的所属文章
			entity.setArticleInfo(findById(entity.getComment().getCommentId())
					.getArticleInfo());
		}
		entity.setCreateDate(new Date());
		super.save(entity);
		articleService.updateCommentCount(entity.getArticleInfo()
				.getArticleId());
	}

	@Override
	public void remove(Comment entity) {
		Comment tempComment = findById(entity.getCommentId());
		if (tempComment != null)
			super.remove(tempComment);
		articleService.updateCommentCount(tempComment.getArticleInfo()
				.getArticleId());
	}

	@Override
	public List<Comment> findNew(int count) {
		return commentDao.selectList(1, count, "createDate", "desc");
	}
}
